package hr.tel.fer.projekt;

import java.net.URL;
import java.text.DecimalFormat;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.anddev.android.weatherforecast.weather.GoogleWeatherHandler;
import org.anddev.android.weatherforecast.weather.WeatherCurrentCondition;
import org.anddev.android.weatherforecast.weather.WeatherForecastCondition;
import org.anddev.android.weatherforecast.weather.WeatherSet;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class ContextWeather {
	public static WeatherCurrentCondition today;
	public static WeatherForecastCondition tomorrow;
	
	//add format: <lat>,<long>
	private static final String GOOGLE_WEATHER_API_URL = "http://www.google.com/ig/api?weather=,,,";
	
	/**
	 * Determines weather data for specified location. Return <i>true</i> if context succesfully determined, <i>false</i> instead.
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public static boolean determineWeatherContext(double latitude, double longitude){
		try {
			//prepare URL
			String preparedUrl = GOOGLE_WEATHER_API_URL+prepareCoordinate(latitude)+","+prepareCoordinate(longitude);
			Log.i("determineWeatherContext-url", ""+preparedUrl);
			
			
            /* Create a URL we want to load some xml-data from. */
            URL url = new URL(preparedUrl);
        

            /* Get a SAXParser from the SAXPArserFactory. */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            /* Get the XMLReader of the SAXParser we created. */
            XMLReader xr = sp.getXMLReader();
            /* Create a new ContentHandler and apply it to the XML-Reader*/
            GoogleWeatherHandler myExampleHandler = new GoogleWeatherHandler();
            xr.setContentHandler(myExampleHandler);
           
            /* Parse the xml-data from our URL. */
            xr.parse(new InputSource(url.openStream()));
            /* Parsing has finished. */

            WeatherSet weatherSet = myExampleHandler.getWeatherSet();
            today = weatherSet.getWeatherCurrentCondition();
            tomorrow = weatherSet.getWeatherForecastCondition(WeatherSet.TODAY_PLUS_1);
            
            if(today!=null && tomorrow!=null){
            	return true;
            }
            else
            	return false;
            
    } catch (Exception e) {
    	Log.e("determineWeatherContext", "error while determin weather context.");
    	e.printStackTrace();
    	return false;
    }
	}
	
	private static String prepareCoordinate(double coordinate){
		DecimalFormat df = new DecimalFormat("#########");
		
		return df.format(coordinate * 1000000);
	}

}
